<template>
  <div class="app-container">
    <!-- 顶部状态栏 -->
    <div class="header">
      <StatusDisplay
        :position="currentPositionData"
        :is-connected="overallConnected"
        @open-settings="openSettings"
      />

      <!-- 缺陷查看按钮 -->
      <div class="header-actions">
        <el-button
          type="success"
          @click="navigateToTrading"
          class="trading-btn"
          :icon="TrendCharts"
          size="default"
        >
          交易视图
        </el-button>

        <el-button
          type="primary"
          @click="navigateToDefects"
          class="defects-btn"
          :icon="Search"
        >
          缺陷查看
        </el-button>
      </div>
    </div>

    <!-- 主内容区域 -->
    <div class="main-content">
      <!-- 控制按钮 -->
      <div class="controls">
        <el-button
          class="panel-toggle-btn"
          @click="toggleSidePanel"
        >
          {{ showSidePanel ? "< " : "> " }}
        </el-button>
      </div>

      <!-- 侧边面板 -->
      <div v-show="showSidePanel" class="side-panel">
        <el-tabs v-model="activeTab" type="card" class="side-tabs">
          <el-tab-pane label="报警" name="alarm">
            <AlarmTable
              :alarm-data="alarmData"
              :total="alarmTotal"
              @page-change="handleAlarmPageChange"
              @return-current="handleReturnCurrent"
              @export="handleExportAlarms"
            />
          </el-tab-pane>
        </el-tabs>
      </div>

      <!-- 图表区域 -->
      <div class="chart-area" :class="{ 'full-width': !showSidePanel }">
        <ChartRenderer
          v-if="!pauseRendering"
          ref="chartRenderer"
          :option="chartOption"
          :data="chartData"
          :selected-channels="selectedChannels"
          :mark-points="markPoints"
          :scroll-position="scrollPosition"
          @chart-ready="handleChartReady"
          @data-zoom="handleDataZoom"
          @click="handleChartClick"
          @scroll-change="handleScrollChange"
          @pause-render="handlePauseRender"
        />
      </div>
    </div>

    <!-- 底部状态栏 -->
    <div class="footer">
      <!-- 可以添加其他状态信息 -->
    </div>
    
    <!-- 设置对话框 -->
    <el-dialog
      v-model="dialogVisible"
      title="系统配置"
      width="1200px"
      @close="closeDialog"
      @opened="openDialog"
    >
      <el-tabs tab-position="left" style="height: 500px">
        <el-tab-pane label="报警参数设置">
          <AlarmSettings
            @settings-change="handleSettingsChange"
          />
        </el-tab-pane>
        <el-tab-pane label="图表展示信息配置">
          <ChannelConfig
            :channels="channelsList"
            @confirm="handleChannelConfirm"
            @color-change="handleColorChange"
            @type-change="handleTypeChange"
            @selection-change="handleSelectionChange"
            @reset="handleChannelReset"
          />
        </el-tab-pane>
      </el-tabs>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted, watch, nextTick } from 'vue'
import { useRouter } from 'vue-router'
import { Search, TrendCharts } from '@element-plus/icons-vue'
import ChartRenderer from '@/components/ChartRenderer.vue'
import ChannelConfig from '@/components/ChannelConfig.vue'
import StatusDisplay from '@/components/StatusDisplay.vue'
import AlarmTable from '@/components/AlarmTable.vue'
import AlarmSettings from '@/components/AlarmSettings.vue'
import { useWebSocket } from '@/composables/useWebSocket'
import { useChartConfig } from '@/composables/useChartConfig'
import { useDataProcessor } from '@/composables/useDataProcessor'
import {
  locateStore,
  initLocateService,
  connectLocateWebSocket,
  disconnectLocateWebSocket,
  getPositionForStatusDisplay
} from '@/services/locateService'
import type { Channel } from '@/types/chart'

// 路由
const router = useRouter()

// WebSocket数据管理
const {
  isConnected,
  chartData,
  alarmData,
  connectWebSockets,
  disconnectWebSockets
} = useWebSocket()

// 图表配置管理
const {
  channelsList,
  selectedChannels,
  showSpeedChart,
  scrollPosition,
  generateEChartsOption,
  updateChannelColor,
  toggleChannelSelection,
  toggleSpeedDisplay,
  confirmChannelConfig,
  updateScrollPosition
} = useChartConfig()

// 数据处理
const {
  markPointXList,
  markPointYList,
  markPointPolXList,
  markPointPolYList,
  processRealtimeData,
  cleanupMarkPoints,
  mapDataToSeries,
  getMarkPointsForChannel
} = useDataProcessor()

// 界面状态
const showSidePanel = ref(true)
const dialogVisible = ref(false)
const activeTab = ref('alarm')
const alarmTotal = ref(0)
const chartRenderer = ref()
const pauseRendering = ref(false) // 暂停渲染标志

// 位置数据计算属性
const currentPositionData = computed(() => {
  return getPositionForStatusDisplay()
})

// 连接状态计算属性
const overallConnected = computed(() => {
  return isConnected.value || locateStore.status.isConnected
})
// 计算属性
const chartOption = computed(() => {
  const option = generateEChartsOption(chartData.value.X, scrollPosition.value)
  console.log('chartOption computed 更新，当前选中通道:', selectedChannels.value.map(c => c.name))
  return option
})

const markPoints = computed(() => {
  const points: Array<{
    channelIndex: number
    points: Array<{ coord: [string | number, number] }>
    type: 'support' | 'suspension'
  }> = []

  selectedChannels.value.forEach((channel, index) => {
    // 添加吊悬点
    if (channel.name.includes('拉出值') && markPointXList.value.length > 0) {
      points.push({
        channelIndex: index,
        points: markPointXList.value,
        type: 'suspension'
      })
    }
    if (channel.name.includes('导高') && markPointYList.value.length > 0) {
      points.push({
        channelIndex: index,
        points: markPointYList.value,
        type: 'suspension'
      })
    }

    // 添加支柱点
    if (channel.name.includes('拉出值') && markPointPolXList.value.length > 0) {
      points.push({
        channelIndex: index,
        points: markPointPolXList.value,
        type: 'support'
      })
    }
    if (channel.name.includes('导高') && markPointPolYList.value.length > 0) {
      points.push({
        channelIndex: index,
        points: markPointPolYList.value,
        type: 'support'
      })
    }
  })

  return points
})


// 事件处理
const navigateToTrading = () => {
  router.push('/trading')
}

const navigateToDefects = () => {
  router.push('/police')
}

const openSettings = () => {
  dialogVisible.value = true
  // 打开设置对话框时暂停渲染
  pauseRendering.value = true
}

const closeDialog = () => {
  dialogVisible.value = false
  // 关闭对话框时恢复渲染
  nextTick(() => {
    pauseRendering.value = false
  })
}

const openDialog = () => {
  // 加载配置数据
}

const toggleSidePanel = () => {
  showSidePanel.value = !showSidePanel.value
  // 延迟调整图表大小以等待DOM更新
  setTimeout(() => {
    chartRenderer.value?.resizeChart()
  }, 300)
}

const handleChannelConfirm = (channels: Channel[]) => {
  // 确认配置并重新生成图表
  confirmChannelConfig()

  // 恢复渲染
  pauseRendering.value = false

  // 强制触发图表更新
  nextTick(() => {
    chartRenderer.value?.resizeChart()
  })

  // 关闭对话框
  dialogVisible.value = false
}

const handleColorChange = (channel: Channel, color: string) => {
  updateChannelColor(channel, color)
}

const handleTypeChange = (channel: Channel) => {
  // 处理图表类型变化
}

const handleSelectionChange = (channel: Channel) => {
  console.log(`App.vue: 收到选择变化事件，通道 ${channel.name}，状态: ${channel.selected}`)
  toggleChannelSelection(channel)
}

const handleChannelReset = () => {
  // 重置通道配置 - 只选中拉出值、导高、磨耗表
  channelsList.forEach(channel => {
    if (channel.name === '拉出值' || channel.name === '导高' || channel.name === '磨耗表') {
      channel.selected = true
    } else {
      channel.selected = false
    }
  })
}

const handleSettingsChange = (settings: any) => {
  // 处理设置变化
}

const handleAlarmPageChange = (page: number) => {
  // 处理报警数据分页
}

const handleReturnCurrent = () => {
  // 返回实时数据显示
}

const handleExportAlarms = () => {
  // 导出报警数据
}

const handleChartReady = (chart: any) => {
  console.log('图表已就绪', chart)
}

const handleDataZoom = (params: any) => {
  console.log('数据缩放', params)
}

const handleChartClick = (params: any) => {
  console.log('图表点击', params)
}

// 处理滚动变化
const handleScrollChange = (position: number) => {
  updateScrollPosition(position)
}

// 处理暂停/恢复渲染
const handlePauseRender = (pause: boolean) => {
  pauseRendering.value = pause
}

// 监听数据变化
watch(chartData, (newData) => {
  // 处理实时数据
  processRealtimeData(newData)
  cleanupMarkPoints(newData.X)
}, { deep: true })

// 生命周期
onMounted(() => {
  // 初始化位置数据服务
  initLocateService()

  // 连接WebSocket
  connectWebSockets()

  // 连接位置WebSocket
  connectLocateWebSocket()

  // 初始化图表配置
  confirmChannelConfig()
})

onUnmounted(() => {
  disconnectWebSockets()
  disconnectLocateWebSocket()
})
</script>

<style scoped>
.app-container {
  width: 100vw;
  height: 100vh;
  background: linear-gradient(to right, rgb(49, 89, 141), #2b6e9b, rgb(49, 89, 141));
  display: flex;
  flex-direction: column;
}

.header {
  height: 80px;
  padding: 0 20px;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.header-actions {
  display: flex;
  align-items: center;
  gap: 15px;
}

.trading-btn {
  background-color: #67c23a;
  border-color: #67c23a;
  color: white;
  font-weight: 500;
}

.defects-btn {
  background-color: #409eff;
  border-color: #409eff;
  color: white;
  font-weight: 500;
}

.main-content {
  flex: 1;
  display: flex;
  position: relative;
  overflow: hidden;
}

.controls {
  position: absolute;
  right: 20px;
  bottom: 80px;
  z-index: 10;
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.speed-toggle-btn {
  background-color: #409eff;
  border-color: #409eff;
}

.nav-btn {
  background-color: #67c23a;
  border-color: #67c23a;
  color: white;
}

.panel-toggle-btn {
  width: 40px;
  background-color: rgb(92, 150, 76);
  border-color: rgb(92, 150, 76);
}

.side-panel {
  width: 300px;
  background-color: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  border-right: 1px solid rgba(255, 255, 255, 0.2);
  flex-shrink: 0;
  transition: all 0.3s ease;
}

.chart-area {
  flex: 1;
  padding: 10px;
  transition: all 0.3s ease;
}

.chart-area.full-width {
  width: 100%;
}

.footer {
  height: 40px;
  background-color: rgb(92, 150, 76);
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
}

.side-tabs {
  height: 100%;
}

:deep(.el-tabs__content) {
  height: calc(100% - 40px);
  overflow-y: auto;
}
</style>